package top.winshu.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.winshu.common.web.context.RequestContextUtil;
import top.winshu.common.web.upload.UploadHelper;
import top.winshu.common.web.upload.UploadResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author winshu
 * @since 2021/12/2
 **/
@Controller
@RequestMapping(value = "/demo")
public class DemoController {

    @Resource
    private UploadHelper uploadHelper;

    @GetMapping(value = "/")
    public String index() {
        return "index";
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public UploadResult upload(@RequestParam("file") MultipartFile multipartFile) {
        return uploadHelper.uploadImage(multipartFile, "aaa");
    }

    @PostMapping(value = "/upload2")
    @ResponseBody
    public List<UploadResult> upload2(@RequestParam("file") MultipartFile[] multipartFiles) {
        // 支持获取 RequestHeader
        System.out.println(RequestContextUtil.getHeader("token"));
        List<UploadResult> results = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            results.add(uploadHelper.upload(multipartFile, "aaa"));
        }
        return results;
    }

    @GetMapping(value = "/attachment")
    public void viewImage(@RequestParam("path") String filePath, HttpServletResponse response) {
        uploadHelper.loadFile(response, filePath, true);
    }
}
